package com.admin.util;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {

	private static final String randChars = "0123456789abcdefghigklmnopqrstuvtxyzABCDEFGHIGKLMNOPQRSTUVWXYZ";
	private static Random random = new Random();
	// 邮箱正则表达式
	private static String emailRegex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{ueditor,}$";
	// 手机号码表达式
	private static String mobileRegex = "^((1[3-9][0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";

	private static final String sftpImgUrl = "/home/images";
	/**
	 * 上传文件路径
	 */
	private static final String uploadFileUrl = "E:/file";
	/**
	 * 判断是否为空
	 * @param obj Object
	 * @return 空 = true，不为空 = false
	 */
	public static boolean isEmpty(Object obj) {
		if (obj == null) {
			return true;
		} else if (obj instanceof String && (obj.equals("") )) {
			return true;
		} else if (obj instanceof Boolean && !((Boolean) obj)) {
			return true;
		} else if (obj instanceof Collection && ((Collection<?>) obj).isEmpty()) {
			return true;
		} else if (obj instanceof Map && ((Map<?,?>) obj).isEmpty()) {
			return true;
		} else if (obj instanceof Object[] && ((Object[]) obj).length == 0) {
			return true;
		}
		if("null".equals(obj)){
			return true;
		}
		return false;
	}
	
	/**
	 * 获取随机字符
	 * @param length 随机字符长度
	 * @param isOnlyNum 是否只是数字
	 * @return 随机字符串
	 */
	public static String getRandStr(int length, boolean isOnlyNum) {
		int size = isOnlyNum ? 10 : 62;
		StringBuffer hash = new StringBuffer(length);
		for (int i = 0; i < length; i++) {
			hash.append(randChars.charAt(random.nextInt(size)));
		}
		return hash.toString();
	}
	
	/**
	 * 验证邮箱格式
	 * @param email 待验证的字符串
	 * @return 如果是符合邮箱格式的字符串,返回<b>true</b>,否则为<b>false</b>
	 */
	public static boolean isEmail(String email) {
		return match(emailRegex, email);
	}

	/**
	 * 验证手机号码
	 * @param mobiles 待验证的字符串
	 * @return 如果是符合手机号码格式的字符串,返回<b>true</b>,否则为<b>false</b>
	 */
	public static boolean isMobile(String mobiles) {
		return match(mobileRegex, mobiles);
	}

	/**
	 * @param regex 正则表达式字符串
	 * @param str 要匹配的字符串
	 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
	 */
	private static boolean match(String regex, String str) {
		if(isEmpty(str)){
			return false;
		}
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}
	
	/**
	 * 获取IP4
	 * @param request
	 * @return IP地址
	 */
	public static String getIP4(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if ("0:0:0:0:0:0:0:1".equals(ip)) {
			ip = "本地";
		}else
		if (ip.split(",").length > 1) {
			ip = ip.split(",")[0];
		}
        return ip;
    }
	
	/**
	 * 数组根据表达式转换为String
	 * @param list
	 * @param exp
	 * @return
	 */
	public static String listToString(List<?> list , String exp) {
		StringBuffer resourceIdsSB = new StringBuffer();
		for (int i = 0; i < list.size(); i++) {
			resourceIdsSB.append(list.get(i));
			if(i < list.size() -1){
				resourceIdsSB.append(exp);
			}
		}
		return resourceIdsSB.toString();
	}

	public static synchronized String createOrderID(){
		Random random = new Random();
		Integer number = random.nextInt(900000) + 100000;
		return System.currentTimeMillis() + String.valueOf(number);
	}
	/**
	 * 生成密码
	 */
	public static String createPassword(String username,String password){
		return   Md5Util.encode(username+password);
	}

	public final static Integer psInt(Object obj){
		if(obj==null||"".equals(obj.toString()))
			return null;
		return Integer.parseInt(obj.toString());
	}

	public final static String psString(Object obj){
		return obj==null ? null:obj.toString();
	}

	public final static Long psLong(Object obj){
		if(obj==null||"".equals(obj.toString()))
			return null;
		return Long.parseLong(obj.toString());
	}

	public final static Float psFloat(Object obj){
		if(obj==null||"".equals(obj.toString()))
			return null;
		return Float.parseFloat(obj.toString());
	}

	public final static Short psShort(Object obj){
		if(obj==null||"".equals(obj.toString()))
			return null;
		return Short.parseShort(obj.toString());
	}

	/**
	 * 获取一定长度的随机字符串
	 * @param length 指定字符串长度
	 * @return 一定长度的字符串
	 */
	public static String getRandomStringByLength(int length) {
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	/**
	 * 根据单号生成下一个取单号
	 * @param no
	 * @return
	 */
	public static String takeCode(String no){
		String zms[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
		String tackCode="A01";
		if(CommonUtil.isEmpty(no)){
			return tackCode;
		}
		String zm=no.substring(0,1);
		Integer num=Integer.parseInt(no.substring(1,no.length()));
		if(num<99){
			num++;
			if(num<10){
				tackCode=zm+"0"+num;
			}else {
				tackCode=zm+num;
			}
		}else {
			for (int i=0;i<zms.length;i++){
				if(zm.equals(zms[i])){
					zm=zms[i+1];
					return zm+"01";
				}
			}
		}
		return tackCode;
	}
	public static String dateToStr(Date datetime) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(datetime);
		return dateString;
	}

	public static Date strToDate(String strDate)throws Exception {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return formatter.parse(strDate);
	}

	//生成16位随机数字码
	public static String getSixteenByUUId() {
		int random = (int) (Math.random()*9+1);
		String valueOf = String.valueOf(random);
		//生成uuid的hashCode值
		int hashCode = UUID.randomUUID().toString().hashCode();
		//可能为负数
		if(hashCode<0){
			hashCode = -hashCode;
		}
		String value = valueOf + String.format("%015d", hashCode);
		return value;
	}

}
